package com.customization.proxy.impl;


import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.rsa.security.RSA;
import weaver.sm.SM4Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WeaIocReplaceComponent("")
public class PorxyIsWeakPassword {


    @WeaReplaceAfter(value = "/api/hrm/password/changePassword", order = 1)
    public String afterSaveLoginId(WeaAfterReplaceParam weaAfterReplaceParam) {
        String loginid = Util.null2String(weaAfterReplaceParam.getParamMap().get("loginid"));
        //设置找回密码是的loginid到登录名
        weaAfterReplaceParam.getRequest().getSession(true).setAttribute("weaver_forgetLoginId", loginid);
        String data = weaAfterReplaceParam.getData();
        return data;
    }


    @WeaReplaceAfter(value = "/api/hrm/password/isWeakPassword", order = 1)
    public String afterExceute(WeaAfterReplaceParam weaAfterReplaceParam) {

        String data = weaAfterReplaceParam.getData();//这个就是接口执行完的报文
        JSONObject obj = JSONObject.fromObject(data);

        Map param = weaAfterReplaceParam.getParamMap();
        String password = Util.null2String(param.get("password"));
        String isrsaopen = Util.null2String(Prop.getPropValue("openRSA", "isrsaopen"));
        ArrayList arrayList = new ArrayList();
        if ("1".equals(isrsaopen)) {
            arrayList.add(password);
            RSA var13 = new RSA();
            List var14 = var13.decryptList(weaAfterReplaceParam.getRequest(), arrayList);
            password = (String) var14.get(0);
        }
        if (password.endsWith("_random_")) {
            SM4Utils var17 = new SM4Utils();
            BaseBean var18 = new BaseBean();
            String var15 = Util.null2String(var18.getPropValue("weaver_client_pwd", "key"));
            if (!"".equals(var15)) {
                password = password.substring(0, password.lastIndexOf("_random_"));
                password = var17.decrypt(password, var15);
            }
        }
        //从找回密码里面配置
        String loginid = Util.null2String(weaAfterReplaceParam.getRequest().getSession(true).getAttribute("weaver_forgetLoginId"));


        if (loginid.equals("")) {
            weaver.hrm.User user = weaver.hrm.HrmUserVarify.getUser
                    (weaAfterReplaceParam.getRequest(), weaAfterReplaceParam.getResponse());
            if (user != null) {
                loginid = user.getLoginid();
            }
        }


        //如果系统校验不是弱密码 走自定义逻辑
        if (!obj.getBoolean("isWeakPassword")) {
            boolean flag = false;
            //todo

            JSONObject res = checkWeakPassword(password);
            if (res.getBoolean("status")) {
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", res.getString("msg"));//
            } else {
                JSONObject objres = checkPersonInfo(loginid, password);
                obj.put("isWeakPassword", objres.get("isWeakPassword"));//
                obj.put("errormsg", objres.getString("errormsg"));//
            }
        }
        obj.put("customDesc", "PorxyIsWeakPassword 20220323");
        return obj.toString();
    }


    /**
     * @param loginid  登录名
     * @param password 密码
     * @return
     */
    public static JSONObject checkPersonInfo(String loginid, String password) {
        JSONObject obj = new JSONObject();
        obj.put("isWeakPassword", false);//键盘逻辑规则不满足条件;
        obj.put("errormsg", "");

        String mobile = "";//手机号码
        String mobilecall = "";//其他号码
        String telephone = "";//电话号码
        String birthday = "";//生日
        String certificatenum = "";//身份证
        String workcode = "";//身份证

        RecordSet rs = new RecordSet();
        rs.execute(" select * from  hrmresource where loginid='" + loginid + "'");
        if (rs.next()) {
            birthday = rs.getString("birthday");
            mobile = rs.getString("mobile");
            mobilecall = rs.getString("mobilecall");
            telephone = rs.getString("telephone");
            certificatenum = rs.getString("certificatenum");
            workcode = rs.getString("workcode");
        }

        boolean flag = false;
        if (!flag && "Y".equals(CHECK_HAS_LOGINID)) {
            int num = Integer.parseInt(LIMIT_NUM_LOGINID);
            if (checkContainWords(password, loginid, num)) {
                flag = true;
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", "密码不能包含登录名中任何连续" + LIMIT_NUM_LOGINID + "位字符");
                if (num == 0) {
                    obj.put("errormsg", "密码不能包含登录名");
                }

            }
        }
        if (!flag && "Y".equals(CHECK_HAS_BIRTHDAY)) {

            int num = Integer.parseInt(LIMIT_NUM_BIRTHDAY);
            if (checkContainWords(password, birthday.replace("-", ""), num)) {
                flag = true;
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", "密码不能包含生日中任何连续" + LIMIT_NUM_BIRTHDAY + "位字符");
                if (num == 0) {
                    obj.put("errormsg", "密码不能包含生日");
                }

            }
        }

        if (!flag && "Y".equals(CHECK_HAS_MOBILE)) {
            int num = Integer.parseInt(LIMIT_NUM_MOBILE);
            if (checkContainWords(password, mobile.replace("-", ""), num)) {
                flag = true;
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", "密码不能包含手机号码中任何连续" + LIMIT_NUM_MOBILE + "位字符");
                if (num == 0) {
                    obj.put("errormsg", "密码不能包含手机号码");
                }

            }
        }

        if (!flag && "Y".equals(CHECK_HAS_MOBILECALL)) {
            int num = Integer.parseInt(LIMIT_NUM_MOBILECALL);
            if (checkContainWords(password, mobilecall.replace("-", ""), num)) {
                flag = true;
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", "密码不能包含其他号码中任何连续" + LIMIT_NUM_MOBILECALL + "位字符");
                if (num == 0) {
                    obj.put("errormsg", "密码不能包含其他号码");
                }

            }
        }

        if (!flag && "Y".equals(CHECK_HAS_TELEPHONE)) {
            int num = Integer.parseInt(LIMIT_NUM_TELEPHONE);
            if (checkContainWords(password, telephone.replace("-", ""), num)) {
                flag = true;
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", "密码不能包含座机号码中任何连续" + LIMIT_NUM_TELEPHONE + "位字符");
                if (num == 0) {
                    obj.put("errormsg", "密码不能包含座机号码");
                }

            }
        }

        if (!flag && "Y".equals(CHECK_HAS_CERTIFICATENUM)) {
            int num = Integer.parseInt(LIMIT_NUM_CERTIFICATENUM);
            if (checkContainWords(password, certificatenum.replace("-", ""), num)) {
                flag = true;
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", "密码不能包含身份证中任何连续" + LIMIT_NUM_CERTIFICATENUM + "位字符");
                if (num == 0) {
                    obj.put("errormsg", "密码不能包含身份证");
                }

            }
        }


        if (!flag && "Y".equals(CHECK_HAS_WORKCODE)) {
            int num = Integer.parseInt(LIMIT_NUM_WORKCODE);
            if (checkContainWords(password, workcode.replace("-", ""), num)) {
                flag = true;
                obj.put("isWeakPassword", true);//键盘逻辑规则不满足条件;
                obj.put("errormsg", "密码不能包含员工号码中任何连续" + LIMIT_NUM_WORKCODE + "位字符");
                if (num == 0) {
                    obj.put("errormsg", "密码不能包含员工号码");
                }

            }
        }
        return obj;
    }


    /**
     * 是否检测键盘按键横向连续
     */
    public static String CHECK_HORIZONTAL_KEY_SEQUENTIAL = "Y";
    /**
     * 键盘物理位置横向不允许最小的连续个数
     */
    public static String LIMIT_HORIZONTAL_NUM_KEY = "4";

    /**
     * 是否检测键盘按键斜向连续
     */
    public static String CHECK_SLOPE_KEY_SEQUENTIAL = "Y";
    /**
     * 键盘物理位置斜向不允许最小的连续个数
     */
    public static String LIMIT_SLOPE_NUM_KEY = "4";


    /**
     * 是否检测连续字符相同
     */
    public static String CHECK_SEQUENTIAL_CHAR_SAME = "Y";
    /**
     * 密码口令中相同字符不允许最小的连续个数
     */
    public static String LIMIT_NUM_SAME_CHAR = "4";
    /**
     * 是否检测包含登录名
     */
    public static String CHECK_HAS_LOGINID = "Y";

    /**
     * 密码口令中不允许最小包含登录名连续的个数
     */
    public static String LIMIT_NUM_LOGINID = "4";


    public static String CHECK_HAS_BIRTHDAY = "Y";
    public static String LIMIT_NUM_BIRTHDAY = "4";

    public static String CHECK_HAS_MOBILE = "Y";
    public static String LIMIT_NUM_MOBILE = "4";

    public static String CHECK_HAS_MOBILECALL = "Y";
    public static String LIMIT_NUM_MOBILECALL = "4";

    public static String CHECK_HAS_TELEPHONE = "Y";
    public static String LIMIT_NUM_TELEPHONE = "4";

    public static String CHECK_HAS_CERTIFICATENUM = "Y";
    public static String LIMIT_NUM_CERTIFICATENUM = "4";

    public static String CHECK_HAS_WORKCODE = "Y";
    public static String LIMIT_NUM_WORKCODE = "4";


    public PorxyIsWeakPassword() {
        BaseBean bean = new BaseBean();
        CHECK_HORIZONTAL_KEY_SEQUENTIAL = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HORIZONTAL_KEY_SEQUENTIAL");
        LIMIT_HORIZONTAL_NUM_KEY = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_HORIZONTAL_NUM_KEY");
        CHECK_SLOPE_KEY_SEQUENTIAL = bean.getPropValue("cus_CheckWeakPassword", "CHECK_SLOPE_KEY_SEQUENTIAL");
        LIMIT_SLOPE_NUM_KEY = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_SLOPE_NUM_KEY");
        CHECK_SEQUENTIAL_CHAR_SAME = bean.getPropValue("cus_CheckWeakPassword", "CHECK_SEQUENTIAL_CHAR_SAME");
        LIMIT_NUM_SAME_CHAR = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_SAME_CHAR");

        CHECK_HAS_LOGINID = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HAS_LOGINID");
        LIMIT_NUM_LOGINID = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_LOGINID");

        CHECK_HAS_BIRTHDAY = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HAS_BIRTHDAY");
        LIMIT_NUM_BIRTHDAY = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_BIRTHDAY");

        CHECK_HAS_MOBILE = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HAS_MOBILE");
        LIMIT_NUM_MOBILE = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_MOBILE");

        CHECK_HAS_MOBILECALL = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HAS_MOBILECALL");
        LIMIT_NUM_MOBILECALL = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_MOBILECALL");

        CHECK_HAS_TELEPHONE = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HAS_TELEPHONE");
        LIMIT_NUM_TELEPHONE = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_TELEPHONE");

        CHECK_HAS_CERTIFICATENUM = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HAS_CERTIFICATENUM");
        LIMIT_NUM_CERTIFICATENUM = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_CERTIFICATENUM");

        CHECK_HAS_WORKCODE = bean.getPropValue("cus_CheckWeakPassword", "CHECK_HAS_WORKCODE");
        LIMIT_NUM_WORKCODE = bean.getPropValue("cus_CheckWeakPassword", "LIMIT_NUM_WORKCODE");


    }


    /**
     * 键盘横向方向规则
     */
    public static String[] KEYBOARD_HORIZONTAL_ARR = {"`01234567890-=", "qwertyuiop[]\\", "asdfghjkl;'", "zxcvbnm,./", "0987654321`", "\\][poiuytrewq"
            , "';lkjhgfdsa", "/.,mnbvcxz"};
    /**
     * 键盘斜线方向规则
     */
    public static String[] KEYBOARD_SLOPE_ARR = {"1qaz", "2wsx", "3edc", "4rfv", "5tgb", "6yhn", "7ujm", "8ik,", "9ol.",
            "0p;/", "=[;.", "-pl,", "0okm", "9ijn", "8uhb", "7ygv", "6tfc", "5rdx", "4esz"};


    /**
     * 检查密码是否包含某个关键字的指定位置
     *
     * @param password
     * @param keys
     * @param num
     * @return
     */
    public static boolean checkContainWords(String password, String keys, int num) {
        boolean res = false;
        int length = keys.length();
        if (length >= num) {
            for (int i = 0; i <= length - num; i++) {
                if (password.toLowerCase().contains(keys.substring(i, i + num).toLowerCase())) {
                    res = true;
                    break;
                }
            }
        }
        return res;
    }

    /**
     * @return 符合要求 返回true
     * @brief 评估密码中包含的字符类型是否符合要求
     * @param[in] password            密码字符串
     */
    public static JSONObject checkWeakPassword(String password) {
        JSONObject res = new JSONObject();
        res.put("pwd", password);
        if (password == null || "".equals(password)) {
            res.put("status", false);
            res.put("msg", "密码不能为空");
            return res;
        }
        boolean flag = false;

        /**
         * 检测是否包含用户名
         */
        if ("Y".equals(CHECK_HORIZONTAL_KEY_SEQUENTIAL)) {
            flag = checkLateralKeyboardSite(password);
            if (flag) {
                res.put("status", flag);
                res.put("msg", "键盘横向连续不允许超过" + LIMIT_SLOPE_NUM_KEY + "个字符");
                return res;
            }
        }

        /**
         * 检测键盘横向连续
         */
        if ("Y".equals(CHECK_HORIZONTAL_KEY_SEQUENTIAL)) {
            flag = checkLateralKeyboardSite(password);
            if (flag) {
                res.put("status", flag);
                res.put("msg", "键盘横向连续不允许超过" + LIMIT_SLOPE_NUM_KEY + "个字符");
                return res;
            }
        }

        /**
         * 检测键盘斜向连续
         */
        if ("Y".equals(CHECK_SLOPE_KEY_SEQUENTIAL)) {
            flag = checkKeyboardSlantSite(password);
            if (flag) {
                res.put("status", flag);
                res.put("msg", "键盘斜向连续不允许超过" + LIMIT_SLOPE_NUM_KEY + "个字符");
                return res;
            }
        }


        /**
         * 检测相邻字符是否相同
         */
        if ("Y".equals(CHECK_SEQUENTIAL_CHAR_SAME)) {
            flag = checkSequentialSameChars(password);
            if (flag) {
                res.put("status", flag);
                res.put("msg", "相邻字符相同不能超过" + LIMIT_HORIZONTAL_NUM_KEY + "个字符");
                return res;
            }
        }


        res.put("status", flag);
        res.put("msg", "满足要求");
        return res;
    }


    public static void main(String[] args) {
        System.out.println(checkWeakPassword("aa@1qaz").toString());
        String password = "1jS2d3";
        System.out.println(checkContainWords("100202", "100202", 4));


    }

    /**
     * @return 含有横向连续字符串 返回true
     * @brief 键盘规则匹配器 横向连续检测
     * @param[in] password            密码字符串
     */
    public static boolean checkLateralKeyboardSite(String password) {
        String t_password = new String(password);
        //将所有输入字符转为小写
        t_password = t_password.toLowerCase();
        int n = t_password.length();
        /**
         * 键盘横向规则检测
         */
        boolean flag = false;
        int arrLen = KEYBOARD_HORIZONTAL_ARR.length;
        int limit_num = Integer.parseInt(LIMIT_HORIZONTAL_NUM_KEY);

        for (int i = 0; i + limit_num <= n; i++) {
            String str = t_password.substring(i, i + limit_num);
            String distinguishStr = password.substring(i, i + limit_num);

            for (int j = 0; j < arrLen; j++) {
                String configStr = KEYBOARD_HORIZONTAL_ARR[j];
                String revOrderStr = new StringBuffer(KEYBOARD_HORIZONTAL_ARR[j]).reverse().toString();

                //考虑 大写键盘匹配的情况
                String UpperStr = KEYBOARD_HORIZONTAL_ARR[j].toUpperCase();
                if ((configStr.indexOf(distinguishStr) != -1) || (UpperStr.indexOf(distinguishStr) != -1)) {
                    flag = true;
                    return flag;
                }
                //考虑逆序输入情况下 连续输入
                String revUpperStr = new StringBuffer(UpperStr).reverse().toString();
                if ((revOrderStr.indexOf(distinguishStr) != -1) || (revUpperStr.indexOf(distinguishStr) != -1)) {
                    flag = true;
                    return flag;
                }

            }
        }
        return flag;
    }

    /**
     * @return 含有斜向连续字符串 返回true
     * @brief 键盘规则匹配器 斜向规则检测
     * @param[in] password            密码字符串
     */
    public static boolean checkKeyboardSlantSite(String password) {
        String t_password = new String(password);
        t_password = t_password.toLowerCase();
        int n = t_password.length();
        /**
         * 键盘斜线方向规则检测
         */
        boolean flag = false;
        int arrLen = KEYBOARD_SLOPE_ARR.length;
        int limit_num = Integer.parseInt(LIMIT_SLOPE_NUM_KEY);

        for (int i = 0; i + limit_num <= n; i++) {
            String str = t_password.substring(i, i + limit_num);
            String distinguishStr = password.substring(i, i + limit_num);
            for (int j = 0; j < arrLen; j++) {
                String configStr = KEYBOARD_SLOPE_ARR[j];
                String revOrderStr = new StringBuffer(KEYBOARD_SLOPE_ARR[j]).reverse().toString();


                //考虑 大写键盘匹配的情况
                String UpperStr = KEYBOARD_SLOPE_ARR[j].toUpperCase();
                if ((configStr.indexOf(distinguishStr) != -1) || (UpperStr.indexOf(distinguishStr) != -1)) {
                    flag = true;
                    return flag;
                }
                //考虑逆序输入情况下 连续输入
                String revUpperStr = new StringBuffer(UpperStr).reverse().toString();
                if ((revOrderStr.indexOf(distinguishStr) != -1) || (revUpperStr.indexOf(distinguishStr) != -1)) {
                    flag = true;
                    return flag;
                }

            }
        }
        return flag;
    }


    /**
     * @return 含有aaaa, 1111等连续字符串 返回true
     * @brief 评估aaaa, 1111这样的相同连续字符
     * @param[in] password            密码字符串
     */
    public static boolean checkSequentialSameChars(String password) {
        String t_password = new String(password);
        int n = t_password.length();
        char[] pwdCharArr = t_password.toCharArray();
        boolean flag = false;
        int limit_num = Integer.parseInt(LIMIT_NUM_SAME_CHAR);
        int count = 0;
        for (int i = 0; i + limit_num <= n; i++) {
            count = 0;
            for (int j = 0; j < limit_num - 1; j++) {
                if (pwdCharArr[i + j] == pwdCharArr[i + j + 1]) {
                    count++;
                    if (count == limit_num - 1) {
                        return true;
                    }
                }
            }
        }
        return flag;
    }


}
